package com.cm.kits;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * @author slp
 */
public class ChromeKits {

    public static void killBrowser() {
        ProcessKits.killProcess(Arrays.asList("firefox", "geckodriver", "crashreporter", "chromedriver", "chrome"));
    }

    /**
     * cmd /c dir 是执行完dir命令后关闭命令窗口。
     * cmd /k dir 是执行完dir命令后不关闭命令窗口。
     * cmd /c start dir 会打开一个新窗口后执行dir指令，原窗口会关闭。
     * cmd /k start dir 会打开一个新窗口后执行dir指令，原窗口不会关闭。
     * String cmd="cmd /k "+new File(batPath).getAbsolutePath();
     *
     * @param cmd
     * @return
     */
    //创建浏览器
    public static String utilBrowserStart(String cmd) {
        Runtime rt = Runtime.getRuntime();
        try {
            System.out.println(cmd);
            Process process = rt.exec(cmd);

            // 获取启动返回信息
            InputStreamReader isr = new InputStreamReader(process.getErrorStream());
            BufferedReader br = new BufferedReader(isr);

            long startTime = System.currentTimeMillis();
            String browserWs = "";
            while (true) {
                if (System.currentTimeMillis() - startTime >= 60000 * 2) {
                    break;
                }
                browserWs = br.readLine();
                if (browserWs != null && browserWs.startsWith("DevTools")) {
                    browserWs = browserWs.substring(browserWs.indexOf("ws:"));
                    break;
                } else {
                    Thread.sleep(100);
                }
            }
            if (StringUtils.isEmpty(browserWs)) {
                throw new RuntimeException("初始化chrome失败");
            }
            System.out.println(browserWs);

            return browserWs;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
